"use client"

import { useState } from "react"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Heart, ShoppingCart } from "lucide-react"

interface Product {
  id: number
  name: string
  price: number
  description: string
  image: string
}

export default function HomePage() {
  const [products, setProducts] = useState<(Product & { isInCart: boolean; isFavorite: boolean })[]>(
    initialProducts.map((product) => ({ ...product, isInCart: false, isFavorite: false })),
  )

  const addToCart = async (productId: number) => {
    try {
      const response = await fetch("http://localhost:8091/api/v1/cart/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ productId }),
      })
      if (response.ok) {
        setProducts((prevProducts) =>
          prevProducts.map((product) => (product.id === productId ? { ...product, isInCart: true } : product)),
        )
      } else {
        console.error("Failed to add to cart")
      }
    } catch (error) {
      console.error("Error adding to cart:", error)
    }
  }

  const toggleFavorite = async (productId: number) => {
    try {
      const response = await fetch("http://localhost:8091/api/v1/favorites/toggle", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ productId }),
      })
      if (response.ok) {
        setProducts((prevProducts) =>
          prevProducts.map((product) =>
            product.id === productId ? { ...product, isFavorite: !product.isFavorite } : product,
          ),
        )
      } else {
        console.error("Failed to toggle favorite")
      }
    } catch (error) {
      console.error("Error toggling favorite:", error)
    }
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-8">热门商品</h1>
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
        {products.map((product) => (
          <Card key={product.id} className="group">
            <CardHeader className="p-0">
              <div className="aspect-square relative overflow-hidden rounded-t-lg">
                <img
                  src={product.image || "/placeholder.svg"}
                  alt={product.name}
                  className="object-cover w-full h-full group-hover:scale-105 transition-transform duration-300"
                />
              </div>
            </CardHeader>
            <CardContent className="p-4">
              <CardTitle className="text-lg mb-2">{product.name}</CardTitle>
              <p className="text-2xl font-bold text-blue-600">¥{product.price}</p>
              <p className="text-sm text-muted-foreground mt-2">{product.description}</p>
            </CardContent>
            <CardFooter className="p-4 pt-0 flex gap-2">
              <Button
                className="flex-1 bg-blue-600 hover:bg-blue-700"
                onClick={() => addToCart(product.id)}
                disabled={product.isInCart}
              >
                <ShoppingCart className="w-4 h-4 mr-2" />
                {product.isInCart ? "已加购" : "加入购物车"}
              </Button>
              <Button
                variant="outline"
                size="icon"
                className={`${
                  product.isFavorite
                    ? "border-red-500 text-red-500 hover:bg-red-50"
                    : "border-blue-600 text-blue-600 hover:bg-blue-50"
                }`}
                onClick={() => toggleFavorite(product.id)}
              >
                <Heart className={`w-4 h-4 ${product.isFavorite ? "fill-red-500" : ""}`} />
              </Button>
            </CardFooter>
          </Card>
        ))}
      </div>
    </div>
  )
}

const initialProducts = [
  {
    id: 1,
    name: "美女程序员同款耳机",
    price: 299,
    description: "高品质音效，持久续航",
    image: "/images/pods.png?height=400&width=400",
  },
  {
    id: 2,
    name: "尼康相机",
    price: 599,
    description: "尼康 感动生活",
    image: "/images/banner.png?height=400&width=400",
  },
  {
    id: 3,
    name: "复古台式机",
    price: 1299,
    description: "经典造型，简单优雅",
    image: "/images/computer.png?height=400&width=400",
  },
  {
    id: 4,
    name: "AMD主板",
    price: 1399,
    description: "AMD YES！",
    image: "/images/motherboard.png?height=400&width=400",
  },
  {
    id: 5,
    name: "iPad Pro",
    price: 4399,
    description: "Apple iPad Pro M1芯片",
    image: "/images/ipad.png?height=400&width=400",
  },
]

